<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { getOperationListApi } from '@/api/base'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getOperationListApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data,
      total: res.count
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    fixed: true,
    type: 'selection',
    width: 80,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'index',
    label: t('common.index'),
    type: 'index',
    width: 80,
    fixed: true,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'summary',
    label: '接口',
    minWidth: 180,
    fixed: true
  },
  {
    field: 'request_method',
    minWidth: 80,
    label: '请求方法'
  },
  {
    field: 'status_code',
    minWidth: 80,
    label: '状态码'
  },
  {
    field: 'tags',
    label: '标签',
    minWidth: 100,
    search: {
      hidden: true
    }
  },
  {
    field: 'username',
    minWidth: 140,
    label: '用户',
    slots: {
      default: (data: any) => {
        return <>{`${data.row.username}(${data.row.userid})`}</>
      }
    }
  },
  {
    field: 'client_ip',
    minWidth: 100,
    label: '用户IP'
  },
  {
    field: 'system',
    label: '操作系统',
    minWidth: 100,
    search: {
      hidden: true
    }
  },
  {
    field: 'process_time',
    label: '响应时长',
    minWidth: 160,
    search: {
      hidden: true
    }
  },
  {
    field: 'create_datetime',
    label: '请求时间',
    minWidth: 180,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
      :fit="true"
    />
  </ContentWrap>
</template>
